package com.micromall.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.micromall.common.payment.ISPaymentRequest;
import com.micromall.common.payment.ISPaymentResponse;
import com.micromall.common.payment.dto.response.Body;
import com.micromall.common.payment.dto.response.GateWayRsp;
import com.micromall.common.payment.dto.response.Head;
import com.micromall.common.payment.dto.response.Ips;
import com.micromall.common.utils.*;
import com.micromall.common.utils.IOUtils;
import com.micromall.model.*;
import com.micromall.service.*;
import com.micromall.service.util.JdbcServiceImpl;
import org.apache.commons.io.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedCaseInsensitiveMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeoutException;

/**
 * Created by DanteFung on 2017/7/31.
 */
@Controller
@RequestMapping("/order/payment")
public class ISPaymentController {

    private static Logger logger = LoggerFactory.getLogger(ISPaymentController.class);

    private static String REDIRECT_HOME_PAGE = "redirect:/home/index";

    @Autowired
    private JdbcServiceImpl jdbcService;
    @Autowired
    private IBusiOrderService busiOrderService;
    @Autowired
    private IBusiOrderItemService busiOrderItemService;
    @Autowired
    private IBusiProductService busiProductService;
    @Autowired
    private IAlRegionService alRegionService;
    @Autowired
    private IMiMemberService miMemberService;

    /**
     * <?xml version="1.0" encoding="utf-8"?>

     <Ips>
     <GateWayRsp>
     <head>
     <ReferenceID>1501606096307</ReferenceID>
     <RspCode>000000</RspCode>
     <RspMsg><![CDATA[交易成功！]]></RspMsg>
     <ReqDate>20170802004816</ReqDate>
     <RspDate>20170802004915</RspDate>
     <Signature>40962561a781b02c10979c3c0eb89936</Signature>
     </head>
     <body>
     <MerBillNo>WS20170730170552798003</MerBillNo>
     <CurrencyType>156</CurrencyType>
     <Amount>0.01</Amount>
     <Date>20170802</Date>
     <Status>Y</Status>
     <Msg><![CDATA[支付成功！]]></Msg>
     <IpsBillNo>BO20170802004817088556</IpsBillNo>
     <IpsTradeNo>2017080200483175959</IpsTradeNo>
     <RetEncodeType>17</RetEncodeType>
     <BankBillNo>710023552986</BankBillNo>
     <ResultType>0</ResultType>
     <IpsBillTime>20170802004905</IpsBillTime>
     </body>
     </GateWayRsp>
     </Ips>

     * @param request
     * @return
     */
    @RequestMapping("/result/success")
    // @Transactional /*这个方法允许出现异常~ 更新的表只有一张.*/
    public String paymentResultSuccess(HttpServletRequest request) {
        String memberNo = request.getParameter("memberNo");
        String requestIP = RequestUtil.getIpAddr(request);
        String responseMessage = request.getParameter("paymentResult");
        logger.info(String.format("回调的报文[%s]", responseMessage));
        // 接口日志存储 -- start
        String sysId = buildIdStr("gateway_serial_no");
        jdbcService.getJdbcTemplate().update(String.format(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块", memberNo, DateUtil.getCurrDateStr(DateUtil.DEFAULT_DATE_FORMAT)+"="+responseMessage, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT)));
        // 接口日志存储 -- end
        StringBuffer errorMessage = new StringBuffer();
        if (StringUtils.isBlank(responseMessage)) {
            errorMessage.append("[订单支付结果返回的报文为空！！]");
            logger.info(errorMessage.toString());
        }

        //////////////////////////////////////////////////////////校验开始/////////////////////////////////////////////////////////////////////////////////////
        // 解析返回的报文
        Ips responseEntity = null;
        try{
            responseEntity = XMLUtil.XML2Object(responseMessage, Ips.class);
        } catch (Exception e){
            e.printStackTrace();
            errorMessage.append("[解析订单支付结果返回的报文报错！]");
            System.out.println(errorMessage.toString());
            logger.info(errorMessage.toString());
        }

        // 校验一级节点
        if (null == responseEntity) {
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(),null);
            sysId = buildIdStr("gateway_serial_no");
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块", memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }

        // 校验返回的二级节点
        GateWayRsp gateWayRsp = responseEntity.getGateWayRsp();
        if (null == gateWayRsp) {
            errorMessage.append("[订单支付结果返回的报文的GateWayRsp节点不存在！]");
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(),null);
            sysId = buildIdStr("gateway_serial_no");
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块",memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }

        Body body = gateWayRsp.getBody();
        Head head = gateWayRsp.getHead();
        // 校验Body
        if (null == body) {
            errorMessage.append("[订单支付结果返回的报文的Body节点不存在！]");
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(),null);
            sysId =  buildIdStr("gateway_serial_no");
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块", memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }

        // 校验head
        if (null == head) {
            errorMessage.append("[订单支付结果返回的报文的Head节点不存在！]");
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(),null);
            sysId =  buildIdStr("gateway_serial_no");
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块", memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }

        // Body和Head节点都存在
        String retEncodeType = body.getRetEncodeType();
        // 签名认证
        String md5Digest = ISPaymentRequest.getMD5Digest(XMLUtil.write2XML(body));
        String signature = head.getSignature();
        if ((!ISPaymentResponse.RetEncodeType.Md5.getDesc().equalsIgnoreCase(retEncodeType)) && StringUtils.isBlank(signature) && (!signature.equals(md5Digest))) {
            errorMessage.append("[签名验证失败!]");
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(), null);
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块", memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }

        // 校验订单号
        String merBillNo = body.getMerBillNo();
        if (StringUtils.isBlank(merBillNo)) {
            errorMessage.append("[订单号为空!!]");
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(), null);
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId, "订单支付模块", memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }

        // 校验订单支付状态
        String status = body.getStatus();
        if (ISPaymentResponse.OrderStatus.FAIL.getCode().equalsIgnoreCase(status) ||
                ISPaymentResponse.OrderStatus.DEALING.getCode().equalsIgnoreCase(status)) {
            errorMessage.append(ISPaymentResponse.OrderStatus.getDescByCode(status));
            String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(), null);
            jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId, "订单支付模块", memberNo, jsonResult, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            logger.info(errorMessage.toString());
            System.out.println(errorMessage.toString());
            return REDIRECT_HOME_PAGE;
        }
        //////////////////////////////////////////////////////////校验结束//////////////////////////////////////////////////////////////////////////////////////
        logger.info("开始处理订单....");
        System.out.println("开始处理订单....");
        String currencyType = body.getCurrencyType();
        String amount = body.getAmount();
        String date = body.getDate();
        String msg = body.getMsg();
        String attach = body.getAttach();
        String ipsBillNo = body.getIpsBillNo();
        String ipsTradeNo = body.getIpsTradeNo();
        String bankBillNo = body.getBankBillNo();
        String resultType = body.getResultType();
        String ipsBillTime = body.getIpsBillTime();
        String referenceID = head.getReferenceID();
        String rspCode = head.getRspCode();
        String rspMsg = head.getRspMsg();
        String reqDate = head.getReqDate();
        String rspDate = head.getRspDate();

        logger.info("开始执行同步代码....");
        System.out.println("开始执行同步代码....");
        synchronized (ISPaymentController.class) {
            try {
                EntityWrapper<BusiOrder> ew = new EntityWrapper<>();
                BusiOrder orderQuery = new BusiOrder();
                orderQuery.setOrderNo(merBillNo);
                ew.setEntity(orderQuery);
                List<BusiOrder> list = busiOrderService.selectList(ew);
                BusiOrder order = null;
                if(null != list && list.size()>0){
                    order = list.get(0);
                }
                System.out.println("OrderList:" + list);
                System.out.println("PoOrder:"+ order);
                /**
                 * 订单支付成功：
                 * 1、修改订单状态为已支付
                 * 2、修改支付时间
                 *
                 * 修改会员状态为已激活，active_status=1 , 记录激活时间active_time
                 */
                if (ISPaymentResponse.OrderStatus.SUCCESS.getCode().equalsIgnoreCase(status)) {
                    if (null != order) {
                        logger.info("开始更新订单状态....");
                        System.out.println("开始更新订单状态....");

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                        String targetDate = "";
                        try{
                            SimpleDateFormat _sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                            Date _rspDate = _sdf.parse(rspDate);
                            targetDate = sdf.format(_rspDate);
                        }catch (Exception e){
                            targetDate = sdf.format(new Date());
                        }
                        order.setPayStatus(Dict.BusiOrder.PayStatus.PAYED.getCode());
                        order.setPayTime(targetDate);
                        order.setUpdateaTime(targetDate);
                        order.setStandy5(ipsBillNo);
                        busiOrderService.updateById(order);
                    }

                    // 跳转到龙哥的成功页面.
                    return REDIRECT_HOME_PAGE;
                } else {
                    logger.info("订单状态支付失败开始保存日志....");
                    System.out.println("订单状态支付失败开始保存日志....");
                    // 跳转到龙哥的错误页面.
                    return REDIRECT_HOME_PAGE;
                }
            } catch (Exception e) {
                e.printStackTrace();
                errorMessage.append(String.format("[%s]", e.getMessage()));
                String jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), errorMessage.toString(), null)+"["+DateUtil.getCurrDateStr(DateUtil.DEFAULT_DATE_FORMAT)+"]";
                String newSysId =  buildIdStr("gateway_serial_no");
                jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD, newSysId, "订单支付模块", memberNo, jsonResult , DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
                logger.info(e.getMessage());
                // TODO:跳转页面
            } finally {
                // 同步到OMS系统
                try{
                    poOrderSync(merBillNo, request);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("同步订单失败!-ERROR:[{}]", e.getMessage());
                }
            }
        }
        logger.info("同步代码执行结束....");
        System.out.println("同步代码执行结束....");
        return REDIRECT_HOME_PAGE;
    }

    @RequestMapping("/order/payment/result/fail")
    @Transactional
    public void paymentResultFail(HttpServletRequest request) {
        String requestIP = RequestUtil.getIpAddr(request);
        String responseMessage = request.getParameter("paymentResult");
        logger.info(responseMessage);
        // 接口日志存储 -- start
        String sysId =  buildIdStr("gateway_serial_no");
        jdbcService.getJdbcTemplate().update(SysApiLog.INSERT_NEW_RECORD,sysId,requestIP,"订单支付模块", "", "paymentResultFail():"+DateUtil.getCurrDateStr(DateUtil.DEFAULT_DATE_FORMAT)+"="+responseMessage, DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        // 接口日志存储 -- end
        StringBuffer errorMessage = new StringBuffer();
        if (StringUtils.isBlank(responseMessage)) {
            errorMessage.append("[订单支付结果返回的报文为空！！]");
            logger.info(errorMessage.toString());
        }
        logger.info(JsonResult.toString(JsonResult.SUCCESS.getCode(), "环迅支付回调成功！", request.getParameter("paymentResult")));
//        renderHtml(JsonResult.toString(JsonResult.SUCCESS.getCode(), "环迅支付回调成功！", request.getParameter("paymentResult")));
    }

    private void poOrderSync(String orderId, HttpServletRequest request){
//        String sql = String.format("SELECT A.CALC_DATE, A.GIFT_CODE , A.TOTAL_AMOUNT ,B.* FROM PO_ORDER A , PO_SHIP B WHERE A.ORDER_ID=B.ORDER_ID AND A.ORDER_NO = '%s'",orderId);
//        List<LinkedCaseInsensitiveMap> orders = (List<LinkedCaseInsensitiveMap>)jdbcService.queryForListPage(
//                sql,1,10000);
        EntityWrapper<BusiOrder> orderEW = new EntityWrapper<>();
        BusiOrder orderQuery = new BusiOrder();
        orderQuery.setOrderNo(orderId);
        orderEW.setEntity(orderQuery);
        List<BusiOrder> orders = busiOrderService.selectList(orderEW);
        if(orders == null || orders.size() == 0 || orders.size() > 1){
            logger.error("订单状态异常, " + "订单号:" + orderId + ",  订单数:"+orders.size());
            System.out.println("订单状态异常, " + "订单号:" + orderId + ",  订单数:"+orders.size());
            return;
        }

        BusiOrder poOrder = orders.get(0);

        // 该订单下的产品列表
        List<Map> products = new ArrayList<Map>();
        Map map = null;
        EntityWrapper<BusiOrderItem> orderItemEW = new EntityWrapper<>();
        BusiOrderItem orderItemQuery = new BusiOrderItem();
        orderItemQuery.setOrderId(poOrder.getId());
        orderItemEW.setEntity(orderItemQuery);
        List<BusiOrderItem> busiOrderItems = busiOrderItemService.selectList(orderItemEW);
        if (null != busiOrderItems && !busiOrderItems.isEmpty()) {
            for (BusiOrderItem item : busiOrderItems) {
                map = new HashMap();
                String prodId = item.getProdId();
                BusiProduct busiProductQuery = new BusiProduct();
                busiProductQuery.setId(prodId);
                BusiProduct busiProduct = busiProductService.selectById(busiProductQuery);
                if (null != busiProduct) {
                    map.put("product_no", busiProduct.getProdCode());
                    map.put("quality", item.getSum());
                    products.add(map);
                } else {
                    logger.error("订单号:[{}]- 订单明细ID:[{}]-查无ID为{}的产品", poOrder.getOrderNo(), item.getId(), item.getProdId());
                }
            }
        } else {
            logger.error("查询的订单明细项为空!");
            return;
        }
        logger.info("订单下的产品列表:{}", JSONObject.toJSONString(products));
        // 获取区域编码
        if (StringUtils.isBlank(poOrder.getAreaId())) {
            logger.error("订单{}的区域ID为空!", poOrder.getOrderNo());
            return;
        }
        AlRegion alRegionQuery = new AlRegion();
        alRegionQuery.setRegionId(poOrder.getAreaId());
        AlRegion alRegion = alRegionService.selectById(alRegionQuery);


        Properties prop = new Properties();
        try{
            prop.load(ISPaymentController.class.getClassLoader().getResourceAsStream("conf/request.properties"));
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        StringBuffer requestUrl = new StringBuffer();
        if(prop.getProperty("productMode").equalsIgnoreCase("true")){
            requestUrl.append(prop.get("requestOrderSyncProductURL"));
        }else{
            requestUrl.append(prop.get("requestOrderSyncTestURL"));
        }

        String _result = "";
        try{
            HttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(1500 * 5)
                    .setConnectTimeout(1500 * 5).build();//设置请求和传输超时时间

            HttpPost _post = new HttpPost();

            List<NameValuePair> contents = new ArrayList<NameValuePair>();

            String apiUserCode = prop.getProperty("apiUserCode");
            String apiUserKey = prop.getProperty("apiKey");


            contents.add(new BasicNameValuePair("api_user_code",apiUserCode));
            contents.add(new BasicNameValuePair("order_no",orderId));
            contents.add(new BasicNameValuePair("shop_account_no", poOrder.getStandy5()));
            contents.add(new BasicNameValuePair("user_code",poOrder.getMemberNo()));
            contents.add(new BasicNameValuePair("amount", poOrder.getTotalAmount()));
            contents.add(new BasicNameValuePair("product_info",JSONObject.toJSONString(products)));
            contents.add(new BasicNameValuePair("ship_name",poOrder.getReceiver()));
            contents.add(new BasicNameValuePair("ship_area",alRegion.getRegionCode()));
            contents.add(new BasicNameValuePair("ship_address",poOrder.getAddress2()));
            contents.add(new BasicNameValuePair("ship_mobile",poOrder.getRecPhone()));
            contents.add(new BasicNameValuePair("ship_zipcode",""));
            String strDate = DateUtil.convertDateToStr(new Date(),"yyyyMMddHH:mm:ss");
            contents.add(new BasicNameValuePair("create_time",strDate));
            //发货状态 0:未发货，1:已发货
            contents.add(new BasicNameValuePair("send_status","0"));

            String _key = MD5Util.getMD5String(apiUserCode+apiUserKey+"poSynfd"+orderId+poOrder.getMemberNo()+alRegion.getRegionCode());
            contents.add(new BasicNameValuePair("sign",_key));

            _post.setEntity(new UrlEncodedFormEntity(contents, HTTP.UTF_8));

            _post.setURI(new URI(requestUrl.toString()));
            _post.setConfig(requestConfig);


            logger.info(">>>>>>>>>>>>>>>请求正文:"+new String(org.apache.commons.io.IOUtils.toByteArray(_post.getEntity().getContent()),"UTF-8"));
            System.out.println(">>>>>>>>>>>>>>>请求正文:"+new String(org.apache.commons.io.IOUtils.toByteArray(_post.getEntity().getContent()),"UTF-8"));

            HttpResponse response = httpClient.execute(_post);
            HttpEntity entity = response.getEntity();

            if(!verifysOrderSync(EntityUtils.toString(entity), request))
                throw new Exception("订单同步不成功！请联系客服");
            return;

        }catch (Exception e){
            logger.error(e.getMessage());
            if (e instanceof ConnectTimeoutException){
                logger.error("连接超时, 订单号 : " + orderId);
                String sysId = buildIdStr("gateway_serial_no");
                String memberNo = request.getParameter("memberNo");
                jdbcService.getJdbcTemplate().update(String.format(SysApiLog.INSERT_NEW_RECORD
                        ,sysId
                        ,RequestUtil.getIpAddr(request)
                        ,"订单支付模块-同步订单", memberNo
                        , "连接超时, 订单号 : " + orderId
                        , DateUtil.convertDateToStr(new Date()
                        , DateUtil.DEFAULT_DATE_FORMAT)));

                System.out.println("连接超时, 订单号 : " + orderId);
            } else if (e instanceof TimeoutException){
                logger.error("响应超时,订单号 : " + orderId);
                String sysId = buildIdStr("gateway_serial_no");
                String memberNo = request.getParameter("memberNo");
                jdbcService.getJdbcTemplate().update(String.format(SysApiLog.INSERT_NEW_RECORD
                        ,sysId
                        ,RequestUtil.getIpAddr(request)
                        ,"订单支付模块-同步订单"
                        , memberNo
                        , "响应超时,订单号 : " + orderId
                        , DateUtil.convertDateToStr(new Date()
                        , DateUtil.DEFAULT_DATE_FORMAT)));
                System.out.println("响应超时,订单号 : " + orderId);
            }
        }

    }

    private boolean verifysOrderSync (String jsonStr, HttpServletRequest request){
        logger.info(String.format("返回的报文为：[%s]",jsonStr));
        System.out.println(String.format("返回的报文为：[%s]",jsonStr));
        boolean flag = true;
        JSONObject _json = JSONObject.parseObject(jsonStr);
        String code = _json.getString("xReturn");
        String message = _json.getString("xMsg");

        String memberNo = request.getParameter("memberNo");
        String requestIP = RequestUtil.getIpAddr(request);

        String sysId = buildIdStr("gateway_serial_no");
        String jsonResult = "";

        if(code.equalsIgnoreCase("0")){
            jsonResult = JsonResult.toString(JsonResult.SUCCESS.getCode(), message,null);
        }else{
            flag = false;
            jsonResult = JsonResult.toString(JsonResult.FAIL.getCode(), message,null);
        }

        jdbcService.getJdbcTemplate().update(String.format(SysApiLog.INSERT_NEW_RECORD
                ,sysId
                ,requestIP
                ,"订单支付模块-同步订单"
                , memberNo
                , jsonResult
                , DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT)));

        return flag;
    }

    public String buildIdStr(final String idCode){
        return UUID.randomUUID().toString().replace("-","");
    }

/*    public static final int DATE_FORMAT_no = 0;
    public static final int DATE_FORMAT_yyyy = 1;
    public static final int DATE_FORMAT_yyyyMM = 2;
    public static final int DATE_FORMAT_yyyyMMdd = 3;
    public static final int DATE_FORMAT_yyMMdd = 4;
    public String buildIdStr(final String idCode) {
        Map<String, Object> sysId = jdbcService.getJdbcTemplate().queryForMap("select id_value, date_format, date_value, id_length, prefix, infix, postfix,value_random " +
                " from sys_id where upper(id_code) = upper(?) for update", idCode);

        String msg = "";

        if(sysId == null){
            return msg;
        }
        int dateFormat = sysId.get("date_format") == null ? 0 : Integer.parseInt(sysId.get("date_format").toString());
        int length = sysId.get("id_length") == null ? 0 : Integer.parseInt(sysId.get("id_length").toString());
        long idValue = sysId.get("id_value") == null ? 0 : Long.parseLong(sysId.get("id_value").toString());
        String prefix = sysId.get("prefix") == null ? "" : sysId.get("prefix").toString();
        String postfix = sysId.get("postfix") == null ? "" : sysId.get("postfix").toString();
        String infix = sysId.get("infix") == null ? "" : sysId.get("infix").toString();
        String dateValue = sysId.get("date_value") == null ? "" : sysId.get("date_value").toString();
        int valueRandom = sysId.get("value_random") == null ? 0 : Integer.parseInt(sysId.get("value_random").toString());
        //获取当前日期
        String format = "yyyy";
        if (dateFormat == DATE_FORMAT_yyyy) {
            format = "yyyy";
        } else if (dateFormat == DATE_FORMAT_yyyyMM) {
            format = "yyyyMM";
        } else if (dateFormat == DATE_FORMAT_yyyyMMdd) {
            format = "yyyyMMdd";
        } else if (dateFormat == DATE_FORMAT_yyMMdd) {
            format = "yyMMdd";
        }

        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String date = formatter.format(new Date());

        if(valueRandom==2){
            //完全随机
            idValue=new Double((Math.random()*new Long(StringUtils.leftPad("", length, '9')))).longValue()+1;
            if (dateFormat > DATE_FORMAT_no) {
                dateValue = date;
            }else{
                dateValue = "";
            }
        }else{
            //需要增加的数值
            long needAddValue=1;
            if(valueRandom==1){
                //如果是随机增加数，则生成1-10的随机数
                needAddValue=new Double((Math.random()*9)).longValue()+1;
            }
            if (dateFormat > DATE_FORMAT_no) {
                idValue = idValue + needAddValue;
                if (!dateValue.equals(date)) {
                    idValue = 1;
                    dateValue = date;
                }
            } else {
                idValue = idValue + needAddValue;
                dateValue = "";
            }
        }

        jdbcService.getJdbcTemplate().update(String.format("UPDATE SYS_ID SET ID_VALUE = '%s' , DATE_VALUE = '%s' WHERE ID_CODE = '%s'" , idValue , dateValue , idCode));

        return prefix + dateValue + infix + StringUtils.leftPad(Long.toString(idValue), length, '0') + postfix;
    }*/

}
